package com.zxj.geekstudy.nio;

import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 6.（必做）写一段代码，使用 HttpClient 或 OkHttp 访问  http://localhost:8801 ，代码提交到 GitHub
 */
public class CustomHttpClient {

    public static void main(String[] args) throws IOException {
        new CustomHttpClient().get("http://localhost:8801");
    }

    public byte[] get(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toByteArray(entity);
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
                httpGet.releaseConnection();
            } catch (IOException e) {
                throw e;
            }
        }
    }

    public byte[] get(FullHttpRequest fullRequest, String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("addRequestHead", fullRequest.headers().get("addRequestHead"));
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toByteArray(entity);
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
                httpGet.releaseConnection();
            } catch (IOException e) {
                throw e;
            }
        }
    }
}
